package basicservicelogic

import (
	"context"
	"property_service/dao/model"
	"property_service/utils/BeanUtils"

	"github.com/zeromicro/go-zero/core/logx"
	"property_service/dao/query"
	"property_service/internal/svc"
	"property_service/property_service"
)

type OperationLogPageLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOperationLogPageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OperationLogPageLogic {
	return &OperationLogPageLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// OperationLogPage 分页查询操作日志
func (l *OperationLogPageLogic) OperationLogPage(in *property_service.OperationLogPageReq) (*property_service.OperationLogPageRes, error) {
	// 定义一个操作日志模型对象切片用于存储查询结果
	var data []*model.OperationLog
	// 获取操作日志模型的查询构造器
	m := query.Use(l.svcCtx.Gorm).OperationLog
	// 构建查询条件：根据租户ID查询
	do := m.WithContext(l.ctx).Where(m.TenantID.Eq(in.Where.TenantID))
	// 动态构建查询条件
	if in.Where.ID > 0 {
		do = do.Where(m.ID.Eq(in.Where.ID)) // ID
	} else {
		// 处理字符类型字段，进行模糊查询
		if in.Where.Module != "" {
			do = do.Where(m.Module.Like("%" + in.Where.Module + "%")) // 操作模块
		}
		if in.Where.ModuleName != "" {
			do = do.Where(m.ModuleName.Like("%" + in.Where.ModuleName + "%")) // 操作模块名
		}
		if in.Where.OperationType != "" {
			do = do.Where(m.OperationType.Like("%" + in.Where.OperationType + "%")) // 操作类型
		}
		if in.Where.OperationTarget != "" {
			do = do.Where(m.OperationTarget.Like("%" + in.Where.OperationTarget + "%")) // 操作对象
		}
		if in.Where.OperationContent != "" {
			do = do.Where(m.OperationContent.Like("%" + in.Where.OperationContent + "%")) // 操作内容
		}
		if in.Where.OperationStatus != "" {
			do = do.Where(m.OperationStatus.Like("%" + in.Where.OperationStatus + "%")) // 操作结果
		}
		if in.Where.OperatorName != "" {
			do = do.Where(m.OperatorName.Like("%" + in.Where.OperatorName + "%")) // 操作人姓名
		}
		if in.Where.OperatorIP != "" {
			do = do.Where(m.OperatorIP.Like("%" + in.Where.OperatorIP + "%")) // 操作IP地址
		}
		if in.Where.Remark != "" {
			do = do.Where(m.Remark.Like("%" + in.Where.Remark + "%")) // 备注
		}

		// 处理时间类型字段，进行精确查询
		if in.Where.OperationTime != "" {
			do = do.Where(m.OperationTime.Eq(BeanUtils.GetDateFormat(in.Where.OperationTime))) // 操作时间
		}

		// 处理数字类型字段，进行精确查询
		if in.Where.OperatorID > 0 {
			do = do.Where(m.OperatorID.Eq(in.Where.OperatorID)) // 操作人ID
		}
	}

	// 定义一个变量用于存储总记录数
	var count int64

	// 判断是否需要分页
	if in.Page+in.Limit <= 1 {
		// 如果不需要分页，查询所有记录
		data, _ = do.Find()
		// 设置总记录数为查询结果的长度
		count = int64(len(data))
	} else {
		// 如果需要分页，查询指定页的数据和总记录数
		data, count, _ = do.FindByPage(int((in.Page-1)*in.Limit), int(in.Limit))
	}

	// 将查询结果转换为响应对象
	list, _ := BeanUtils.CopyProperties(data, property_service.OperationLog{})

	// 返回查询结果，包括总记录数和数据列表
	return &property_service.OperationLogPageRes{
		Count: count,
		List:  list.([]*property_service.OperationLog),
	}, nil
}
